<!DOCTYPE html>
<html>

<head>
    <title>糖尿病患者热量摄入计算器</title>
    <style>
        /* * {
            margin: 0;
            padding: 0;
        } */
        body {
            width: 100vw;
            background: linear-gradient(45deg, #6a5acd, #00ced1);
        }

        .btys {
            width: 100vw;
            height: 10vh;
            /* background: #369; */
            line-height: 10vh;
            text-align: center;
            font-size: 64px;
            margin: 0;
            padding: 0;
        }

        .porduct-order-agile {
            width: 90%;
            padding-bottom: 1.5em;
            margin: 1em auto;
            /* -webkit-box-shadow: -2px 7px 37px 8px rgba(0, 0, 0, 0.52);
            -moz-box-shadow: -2px 7px 37px 8px rgba(0, 0, 0, 0.52);
            box-shadow: -2px 7px 37px 8px rgba(0, 0, 0, 0.52); */
            background: #fff;
            border-radius: 15px; /* 圆角边框 */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
            border: 1px solid #ccc; /* 边框颜色 */
        }

        .form-columns {
            display: flex;
            justify-content: center;
        }

        .column {
            width: calc(50% - 15px);
            /* 调整列的宽度，考虑到间隔 */
            /* width: 50%; */
            padding-top: 1.5em;
            margin: 0 auto;
            /* 将列水平居中对齐 */
            padding-left: 3.5em;
        }

        .form-group {
            display: flex;
            align-items: center;
            margin-top: 1em;
            margin-bottom: 1em;
        }

        .form-group p {
            margin: 0;
            /* 移除默认的段落间距 */
            margin-right: 1em;
            /* 添加右侧间距以确保 p 和 input 之间有空隙 */
            color: #000;
            font-size: 18px;
            letter-spacing: .5px;
            text-transform: capitalize;
            white-space: nowrap;
            /* 防止段落文本换行 */
            /* min-width: 100px; 设置一个最小宽度，使对齐更容易 */
            text-align: right;
        }

        .form-group input {
            /* width: 50%; */
            /* flex-grow: 1; */
            /* 使输入框占据剩余的水平空间 */
            /* padding: 0.5em 0em 0em 0.5em; */
            box-sizing: border-box;
            text-align: left;
            font-size: 20px;
            border: 2px solid #000;
            /* 设置边框宽度、样式和颜色 */
            border-radius: 4px;
            /* 可选：增加圆角 */
        }

        .gender,
        .activityLevel,
        .weightGoal {
            font-size: 18px;
            border: 2px solid #000;
            /* 设置边框宽度、样式和颜色 */
            border-radius: 4px;
            /* 可选：增加圆角 */
        }

        .btn-primary {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .btn-gradient {
            background: linear-gradient(45deg, #6a5acd, #00ced1);
            border: none;
            color: white;
            padding: 15px 30px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            border-radius: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .hot-agile { /*第二个*/
            width: 90%;
            padding-top: 1em;
            padding-bottom: 1em;
            margin: 1em auto;
            /* -webkit-box-shadow: -2px 7px 37px 8px rgba(0, 0, 0, 0.52);
            -moz-box-shadow: -2px 7px 37px 8px rgba(0, 0, 0, 0.52);
            box-shadow: -2px 7px 37px 8px rgba(0, 0, 0, 0.52); */
            background: #fff;
            display: flex;
            flex-direction: column;
            border-radius: 15px; /* 圆角边框 */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
            border: 1px solid #ccc; /* 边框颜色 */
        }

        .porduct-order-agile-2 {
            display: flex;
            align-items: flex-end;
            margin: 20px;
        }

        .icon {
            width: 50px;
            /* 调整图标大小 */
            height: 50px;
            margin-right: 10px;
        }

        .porduct-order-agile-2 .line {
            /* flex-grow: 1; */
            width: 100px;
            /* 调整横线的长度 */
            border-bottom: 2px solid #000;
            text-align: center;
            position: relative;
        }

        .porduct-order-agile-2 .text {
            white-space: nowrap;
        }

        .porduct-order-agile-2 .line span {
            /* position: absolute; */
            left: 50%;
            transform: translateX(-50%);
            background: white;
            padding: 0 5px;
        }

        .custom-table {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
        }

        .custom-table th,
        .custom-table td {
            border: 1px solid #000;
            padding: 15px;
            text-align: center;
            font-size: 18px;
        }

        .custom-table th {
            background-color: #f2f2f2;
        }

        .custom-table .cell-content {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .custom-table .cell-content img {
            width: 30px;
            height: 30px;
            margin-right: 10px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
        }

        .selected {
            background-color: #ff0;
        }

        .button-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .submit-button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #6a5acd;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .submit-button:hover {
            background-color: #483d8b;
        }
    </style>
</head>

<body>

    <h1 class='btys'>糖尿病患者热量摄入计算器</h1>
    <div class="porduct-order-agile">
        <form action="#" method="post">
            <div class="form-columns">
                <div class="column">
                    <div class="form-group">
                        <p>性别</p>
                        <select class="gender" name="gender" id="gender">
                            <option value="male">男性</option>
                            <option value="female">女性</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <p>年龄</p>
                        <input type="email" placeholder="输入数字即可" id="age" required="">
                    </div>
                    <div class="form-group">
                        <p>体重</p>
                        <input type="text" name="Phone" placeholder="请输入“kg”为单位的体重" id="weight" required="">
                    </div>
                </div>
                <div class="column">
                    <div class="form-group">
                        <p>身高</p>
                        <input type="text" name="Phone" placeholder="请输入“cm”为单位的身高" id="height" required="">
                    </div>
                    <div class="form-group">
                        <p>活动水平</p>
                        <select class="activityLevel" name="activityLevel" id="activityLevel">
                            <option value="1.2">久坐</option>
                            <option value="1.375">轻度活动</option>
                            <option value="1.55">中度活动</option>
                            <option value="1.725">高度活动</option>
                            <option value="1.9">极度活动</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <p>体重目标</p>
                        <select class="weightGoal" name="weightGoal" id="weightGoal">
                            <option value="maintain">维持体重</option>
                            <option value="lose">减重</option>
                            <option value="gain">增重</option>
                        </select>
                    </div>
                </div>
            </div>
        </form>
        <div class="btn-primary">
            <button type="submit" class="btn-gradient" onclick="calculateCalories()">计算所需热量</button>
        </div>

    </div>

    <div class="hot-agile">
        <div class="porduct-order-agile-2">
            <img src="热量消耗.png" alt="Icon" class="icon">
            <div class="text">每日热量需求：</div>
            <div class="line"><span id="calories"></span></div>
        </div>
        <table class="custom-table">
            <thead>
                <tr>
                    <th colspan="3">宏量营养素分配</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <div class="cell-content">
                            <img src="碳水化合物.png" alt="Icon">
                            <span>碳水化合物</span>
                        </div>
                    </td>
                    <td>
                        <div class="cell-content">
                            <img src="蛋白质.png" alt="Icon">
                            <span>蛋白质</span>
                        </div>
                    </td>
                    <td>
                        <div class="cell-content">
                            <img src="脂肪.png" alt="Icon">
                            <span>脂肪</span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td id="carbs"></td>
                    <td id="protein"></td>
                    <td id="fat"></td>
                </tr>
            </tbody>
        </table>
    </div>
    </div>

    <div class="hot-agile">
        <table id="foodTable">
            <thead>
                <tr>
                    <th colspan="2">请选择食物</th>
                </tr>
            </thead>
            <thead id="tableHead"></thead>
            <tbody id="tableBody"></tbody>
        </table>
        <div class="button-container">
            <button class="submit-button" onclick="calculateFoodWeight()" >计算食物重量</button>
        </div>
    </div>


    <!-- <form id="calorieForm">
        <label for="gender">性别:</label>
        <select id="gender" name="gender">
            <option value="male">男性</option>
            <option value="female">女性</option>
        </select><br><br>

        <label for="age">年龄:</label>
        <input type="number" id="age" name="age" required><br><br>

        <label for="weight">体重（kg）:</label>
        <input type="number" id="weight" name="weight" required><br><br>

        <label for="height">身高（cm）:</label>
        <input type="number" id="height" name="height" required><br><br>

        <label for="activityLevel">活动水平:</label>
        <select id="activityLevel" name="activityLevel">
            <option value="1.2">久坐</option>
            <option value="1.375">轻度活动</option>
            <option value="1.55">中度活动</option>
            <option value="1.725">高度活动</option>
            <option value="1.9">极度活动</option>
        </select><br><br>

        <label for="weightGoal">体重目标:</label>
        <select id="weightGoal" name="weightGoal">
            <option value="maintain">维持体重</option>
            <option value="lose">减重</option>
            <option value="gain">增重</option>
        </select><br><br>

        <button type="button"  onclick="calculateCalories()">计算热量</button>
    </form> -->

    <!-- <h2>每日热量需求: <span id="calories"></span> 千卡</h2>

    <h2>宏量营养素分配:</h2>
    <p>碳水化合物: <span id="carbs"></span> 克</p>
    <p>蛋白质: <span id="protein"></span> 克</p>
    <p>脂肪: <span id="fat"></span> 克</p> -->

    <!-- <h2>选择食物</h2>
    <div id="foodList">
    </div>
    <button type="button" onclick="calculateFoodWeight()">计算食物重量</button> -->


    <div class="hot-agile">
        <table>
            <thead>
                <tr>
                    <th>餐食热量分配</th>
                    <th>食物及其重量</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td id="cell-1-1">早餐重量: <span id="breakfast-weight">200g</span></td>
                    <td id="cell-1-2">
                        <div class="food-weight" id="breakfastFoodWeightList">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td id="cell-2-1">午餐重量: <span id="lunch-weight">300g</span></td>
                    <td id="cell-2-2">
                        <div class="food-weight" id="lunchFoodWeightList">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td id="cell-3-1">晚餐重量: <span id="dinner-weight">250g</span></td>
                    <td id="cell-3-2">
                        <div class="food-weight" id="dinnerFoodWeightList">
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- <h2>餐食热量分配</h2>
    <p>早餐热量: <span id="breakfastCalories"></span> 千卡</p>
    <p>中餐热量: <span id="lunchCalories"></span> 千卡</p>
    <p>晚餐热量: <span id="dinnerCalories"></span> 千卡</p>

    <h2>食物重量</h2>
    <h3>早餐</h3>
    <div id="breakfastFoodWeightList"></div>
    <h3>中餐</h3>
    <div id="lunchFoodWeightList"></div>
    <h3>晚餐</h3>
    <div id="dinnerFoodWeightList"></div> -->

    <script>
        const foodData = [
            { category: "主食类", food: "白米饭", calories: 130 },
            { category: "主食类", food: "全麦面包", calories: 70 },
            { category: "主食类", food: "馒头", calories: 220 },
            { category: "主食类", food: "燕麦片", calories: 379 },
            { category: "主食类", food: "土豆（蒸/煮）", calories: 77 },
            { category: "主食类", food: "玉米（煮）", calories: 96 },
            { category: "蔬菜类", food: "西兰花", calories: 34 },
            { category: "蔬菜类", food: "胡萝卜", calories: 41 },
            { category: "蔬菜类", food: "番茄", calories: 18 },
            { category: "蔬菜类", food: "菠菜", calories: 23 },
            { category: "蔬菜类", food: "黄瓜", calories: 16 },
            { category: "蔬菜类", food: "生菜", calories: 15 },
            { category: "水果类", food: "苹果", calories: 52 },
            { category: "水果类", food: "香蕉", calories: 89 },
            { category: "水果类", food: "橙子", calories: 47 },
            { category: "水果类", food: "草莓", calories: 32 },
            { category: "水果类", food: "西瓜", calories: 30 },
            { category: "水果类", food: "葡萄", calories: 69 },
            { category: "蛋白质类", food: "鸡胸肉（煮）", calories: 165 },
            { category: "蛋白质类", food: "牛肉（煮）", calories: 250 },
            { category: "蛋白质类", food: "鱼（鲑鱼，煮）", calories: 206 },
            { category: "蛋白质类", food: "豆腐", calories: 76 },
            { category: "蛋白质类", food: "鸡蛋", calories: 68 },
            { category: "蛋白质类", food: "豆浆", calories: 33 },
            { category: "奶制品类", food: "牛奶（全脂）", calories: 61 },
            { category: "奶制品类", food: "酸奶（普通）", calories: 59 },
            { category: "奶制品类", food: "奶酪", calories: 402 },
            { category: "奶制品类", food: "脱脂牛奶", calories: 34 },
            { category: "奶制品类", food: "奶粉", calories: 496 },
            { category: "脂肪类", food: "橄榄油", calories: 120 },
            { category: "脂肪类", food: "黄油", calories: 100 },
            { category: "脂肪类", food: "花生酱", calories: 94 },
            { category: "脂肪类", food: "杏仁", calories: 575 },
            { category: "脂肪类", food: "核桃", calories: 654 },
            { category: "脂肪类", food: "腰果", calories: 553 },
            { category: "零食和甜品", food: "巧克力", calories: 546 },
            { category: "零食和甜品", food: "薯片", calories: 536 },
            { category: "零食和甜品", food: "饼干", calories: 502 },
            { category: "零食和甜品", food: "冰淇淋", calories: 207 },
            { category: "零食和甜品", food: "糖果", calories: 394 },
            { category: "饮料类", food: "可乐", calories: 42 },
            { category: "饮料类", food: "果汁", calories: 46 },
            { category: "饮料类", food: "咖啡（无糖）", calories: 2 },
            { category: "饮料类", food: "红茶（无糖）", calories: 1 },
            { category: "饮料类", food: "啤酒", calories: 43 },
            { category: "饮料类", food: "红酒", calories: 85 }
        ];

        let selectedIndices = [];

        // 单元格点击事件处理
        function toggleSelection(event) {
            const foodItem = event.target;
            const index = parseInt(foodItem.dataset.index, 10);

            if (foodItem.classList.contains('selected')) {
                foodItem.classList.remove('selected');
                selectedIndices = selectedIndices.filter(i => i !== index);
            } else {
                foodItem.classList.add('selected');
                selectedIndices.push(index);
            }

            console.log('Selected indices:', selectedIndices);
        }

        function calculateCalories() {
            const gender = document.getElementById("gender").value;
            const age = parseInt(document.getElementById("age").value);
            const weight = parseFloat(document.getElementById("weight").value);
            const height = parseFloat(document.getElementById("height").value);
            const activityLevel = parseFloat(document.getElementById("activityLevel").value);
            const weightGoal = document.getElementById("weightGoal").value;

            let BMR;

            if (gender === "male") {
                BMR = 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age);
            } else {
                BMR = 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age);
            }

            let TEE = BMR * activityLevel;

            // 根据体重目标调整每日热量需求
            if (weightGoal === "lose") {
                TEE -= 500; // 减少500千卡/天
            } else if (weightGoal === "gain") {
                TEE += 500; // 增加500千卡/天
            }

            document.getElementById("calories").textContent = TEE.toFixed(2);

            // 宏量营养素分配
            const carbs = TEE * 0.55 / 4; // 55% 热量来自碳水化合物，每克碳水化合物提供4千卡
            const protein = TEE * 0.15 / 4; // 15% 热量来自蛋白质，每克蛋白质提供4千卡
            const fat = TEE * 0.30 / 9; // 30% 热量来自脂肪，每克脂肪提供9千卡

            document.getElementById("carbs").textContent = carbs.toFixed(2) + ' 克';
            document.getElementById("protein").textContent = protein.toFixed(2) + ' 克';
            document.getElementById("fat").textContent = fat.toFixed(2) + ' 克';

            // 餐食热量分配
            const breakfastCalories = TEE * 0.2;
            const lunchCalories = TEE * 0.4;
            const dinnerCalories = TEE * 0.4;

            document.getElementById("breakfastCalories").textContent = breakfastCalories.toFixed(2);
            document.getElementById("lunchCalories").textContent = lunchCalories.toFixed(2);
            document.getElementById("dinnerCalories").textContent = dinnerCalories.toFixed(2);
        }

        function populateFoodList() {
            // const foodListDiv = document.getElementById("foodList");
            // foodData.forEach((item, index) => {
            //     const checkbox = document.createElement("input");
            //     checkbox.type = "checkbox";
            //     checkbox.id = "food" + index;
            //     checkbox.value = item.food;

            //     const label = document.createElement("label");
            //     label.htmlFor = "food" + index;
            //     label.textContent = `${item.category} - ${item.food} (${item.calories} 千卡/100克)`;

            //     const br = document.createElement("br");

            //     foodListDiv.appendChild(checkbox);
            //     foodListDiv.appendChild(label);
            //     foodListDiv.appendChild(br);
            // });

            const tableHead = document.getElementById('tableHead');
            const tableBody = document.getElementById('tableBody');

            // 提取 category 并去重
            const categories = [...new Set(foodData.map(item => item.category))];

            // 创建表头
            const headerRow = document.createElement('tr');
            headerRow.innerHTML = '<th>Category</th><th>Foods</th>';
            tableHead.appendChild(headerRow);

            // 按 category 分组
            const groupedData = {};
            categories.forEach(category => {
                groupedData[category] = foodData.filter(item => item.category === category);
            });

            // 创建表格内容
            categories.forEach(category => {
                const row = document.createElement('tr');

                // 创建 category 单元格
                const categoryCell = document.createElement('td');
                categoryCell.textContent = category;
                row.appendChild(categoryCell);

                // 创建 food 单元格
                const foodCell = document.createElement('td');
                groupedData[category].forEach(item => {
                    const foodItem = document.createElement('div');
                    foodItem.textContent = `${item.food} (${item.calories} kcal)`;
                    foodItem.dataset.index = foodData.indexOf(item); // 保存原始数组的索引
                    foodItem.id = 'food'+foodItem.dataset.index
                    foodItem.addEventListener('click', toggleSelection);
                    foodCell.appendChild(foodItem);
                });
                row.appendChild(foodCell);

                tableBody.appendChild(row);
            });
        }

        function calculateFoodWeight() {
            const calories = parseFloat(document.getElementById("calories").textContent);
            if (isNaN(calories)) {
                alert("请先计算每日热量需求！");
                return;
            }

            const breakfastCalories = calories * 0.2;
            const lunchCalories = calories * 0.4;
            const dinnerCalories = calories * 0.4;

            // const selectedFoods = foodData.filter((item, index) => document.getElementById("food" + index).checked);
            const selectedFoods = selectedIndices.map(index => foodData[index]);
            console.log(selectedFoods,'select')

            const breakfastFoodWeightListDiv = document.getElementById("breakfastFoodWeightList");
            const lunchFoodWeightListDiv = document.getElementById("lunchFoodWeightList");
            const dinnerFoodWeightListDiv = document.getElementById("dinnerFoodWeightList");

            breakfastFoodWeightListDiv.innerHTML = "";
            lunchFoodWeightListDiv.innerHTML = "";
            dinnerFoodWeightListDiv.innerHTML = "";

            selectedFoods.forEach(item => {
                const breakfastWeight = (breakfastCalories / selectedFoods.length / item.calories) * 100;
                const lunchWeight = (lunchCalories / selectedFoods.length / item.calories) * 100;
                const dinnerWeight = (dinnerCalories / selectedFoods.length / item.calories) * 100;

                const breakfastP = document.createElement("p");
                breakfastP.textContent = `${item.food}: ${breakfastWeight.toFixed(2)} 克`;
                breakfastFoodWeightListDiv.appendChild(breakfastP);

                const lunchP = document.createElement("p");
                lunchP.textContent = `${item.food}: ${lunchWeight.toFixed(2)} 克`;
                lunchFoodWeightListDiv.appendChild(lunchP);

                const dinnerP = document.createElement("p");
                dinnerP.textContent = `${item.food}: ${dinnerWeight.toFixed(2)} 克`;
                dinnerFoodWeightListDiv.appendChild(dinnerP);
            });
        }

        window.onload = populateFoodList;
    </script>
</body>

</html>